﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using RN.ERP.DAL.Context;
using RN.ERP.Entity.Authority;
using Fly.FlyCommon;
using System.Data.Entity;
using RN.ERP.Entity.ZBDLRY;
using RN.ERP.DTO;
using Fly.Log;
using Fly.Common.Linq;

namespace RN.ERP.BLL.LC
{
    public class ProjectBLL : BaseProjectBLL
    {
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }
        public ProjectBLL()
        {
            base.baseContext = new ZBDL_Context();
        }


        #region  项目查询
        public override string ProjectTest(string input)
        {
            try
            {
                return input;
            }
            catch (Exception ex)
            {

                return null;
            }
        }

        public override IList<BzkProject> GetProjectList(int pageCount, int pageSize, string conditions, out int count)
        {
            var projects = dbContext.Projects;
            var corps = dbContext.Corps;
            var managers = dbContext.Managers;

            var query = from b in projects
                        join c in corps on b.ID equals c.ProjectId
                        into leftstr
                        from left1 in leftstr.DefaultIfEmpty()
                        join m in managers on left1.ProjectId equals m.ProjectId
                        into leftstr2
                        from left2 in leftstr2.DefaultIfEmpty()
                        select new BzkProject
                        {
                            ID = b.ID,
                            Title = b.Title,
                            Address = b.Address,
                            Code = b.Code,
                            AreaCode = b.AreaCode,
                            Cost = b.Cost,
                            Areas = b.Areas,
                            FlowCode = b.Code,
                            StartDate = b.StartDate,
                            EndDate = b.EndDate,
                            CorpUserGuid = left1.CorpUserGuid,
                        };
            BzkProject queryproject = JsonConvert.DeserializeObject<BzkProject>(conditions);
            if (queryproject != null)
            {
                if (queryproject.bKind != null)
                {
                    query = query.Where(q => q.bKind == queryproject.bKind);
                }
                if (queryproject.CorpUserGuid != null)
                {
                    query = query.Where(q => q.CorpUserGuid == queryproject.CorpUserGuid);
                }
                if (!string.IsNullOrEmpty(queryproject.Title))
                {
                    query = query.Where(q => q.Title.Contains(queryproject.Title));
                }
            }

            count = query.ToList().Distinct().ToList().Count();
            var bzkquery = query.ToList().Distinct().OrderByDescending(m => m.ID).Skip((pageCount - 1) * pageSize).Take(pageSize);

            List<BzkProject> projectlist = new List<BzkProject>();
            foreach (var item in bzkquery)
            {
                BzkProject project = GetProjectInfoByID(item.ID);
                projectlist.Add(project);
            }
            return projectlist;
        }

        public BzkProject GetProjectInfoByID(int projectid)
        {
            BzkProject project = new BzkProject();
            project.ID = projectid;
            h_projectBzk_New projectinfo = GetProjectInfo(projectid);
            project.Title = projectinfo.Title;
            project.bKind = projectinfo.bKind;
            project.Address = projectinfo.Address;
            project.CorpName = projectinfo.CorpName;
            project.Areas = projectinfo.Areas;
            project.Cost = projectinfo.Cost;
            project.StartDate = projectinfo.StartDate;
            project.EndDate = projectinfo.EndDate;

            //查询 施工主企业（总包）
            h_ProjectCorp corpinfo = GetCorpInfo(projectid, 15, 0);
            if (corpinfo != null)
            {
                project.SGCorpName = corpinfo.CorpName;
                project.TBCorpName = corpinfo.CorpName;
                h_ProjectManager managerinfo = GetManagerInfo(projectid, corpinfo.Id, 1);
                if (managerinfo != null)
                {
                    project.SGCorpManager = managerinfo.ManagerName;
                }
            }


            //查询  监理主企业
            h_ProjectCorp corpinfojl = GetCorpInfo(projectid, 42, 0);
            if (corpinfojl != null)
            {
                project.JLCorpName = corpinfojl.CorpName;
                h_ProjectManager managerinfo = GetManagerInfo(projectid, corpinfojl.Id, 2);
                if (managerinfo != null)
                {
                    project.JLCorpManager = managerinfo.ManagerName;
                }
            }
            return null;
        }

        public h_projectBzk_New GetProjectInfo(int id)
        {
            return dbContext.Projects.Where(p => p.ID == id).FirstOrDefault();
        }

        public h_ProjectCorp GetCorpInfo(int projectid, int corptype, int corptype2)
        {
            return dbContext.Corps.Where(c => c.ProjectId == projectid && c.CorpType == corptype && c.CorpType2 == corptype2).FirstOrDefault();
        }

        public h_ProjectManager GetManagerInfo(int projectid, int corpid, int managertype)
        {
            return dbContext.Managers.Where(m => m.ProjectId == projectid && m.ProjectCorpId == corpid && m.ManagerType == managertype).FirstOrDefault();
        }

        #endregion

        #region 审核
        #endregion

        #region 招标类项目

        public override List<DTO.ZtbJRKBProject> GetJrkbProject(string areaCode, int codeClass)
        {
            List<DTO.ZtbJRKBProject> list = new List<ZtbJRKBProject>();

            DAL.LcDAL.ProjectDAL dal = new DAL.LcDAL.ProjectDAL();
            DataTable dt = dal.GetJrkbProject(areaCode, codeClass);
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    DTO.ZtbJRKBProject project = new ZtbJRKBProject()
                            {
                                ProjectKind = dr["projectkind"].ToString(),
                                ProjectName = dr["ProjectName"].ToString(),
                                ProjectRoom = dr["ProjectRoom"].ToString(),
                                KbDate = DateTime.Parse(dr["KbDate"].ToString())
                            };
                    list.Add(project);
                }
                catch (FormatException)
                {
                    DTO.ZtbJRKBProject project = new ZtbJRKBProject()
                            {
                                ProjectKind = dr["projectkind"].ToString(),
                                ProjectName = dr["ProjectName"].ToString(),
                                ProjectRoom = dr["ProjectRoom"].ToString()
                            };
                    list.Add(project);
                }
            }

            return list;
        }

        #endregion

        #region 省招标代理业绩

        /// <summary>
        /// 获取业绩
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <param name="areaCode"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public override IList<DTO.ProjectRecord> GetyjRecordList(string Code, int pageCount, int pageSize, string conditions, string areaCode, out int count, out double? totalZBMpney)
        {
            count = 0;
            totalZBMpney = 0;
            DateTime contractDate = DateTime.Now.AddYears(-1);
            switch (Code)
            {
                case "DL":
                    var query = from yj in dbContext.dlyjRecord
                                join u in dbContext.T_Sys_Users
                                on yj.CorpGuid equals u.UserGuid
                                join a in dbContext.AreaSSQ
                                    on new
                                    {
                                        Code = yj.pAreaCode,
                                        IsOuter = yj.isOuter

                                    } equals new
                                    {
                                        Code = a.Code,
                                        IsOuter = a.IsOuter
                                    }
                                into ayjs
                                from ayj in ayjs.DefaultIfEmpty()
                                where yj.isOuter == 0 && yj.ContractDate >= contractDate
                                select new DTO.ProjectRecord
                                {
                                    ProjectID = yj.ID,
                                    ProjectName = yj.Project,
                                    AreaCode = yj.pAreaCode,
                                    AreaName = ayj.Title,
                                    wtCorpName = yj.wtCorpName,
                                    NoticeDate = yj.NoticeDate,
                                    CheckCorp = yj.CheckCorp,
                                    ZbMoneyFloat = yj.ZbMoneyFloat,
                                    ContractDate = yj.ContractDate,
                                    NoticeCode = yj.NoticeCode,
                                    FcDate = yj.FcDate,
                                    KbDate = yj.KbDate,
                                    BidNum = yj.BidNum,
                                    isZBTZS = yj.isZBTZS,
                                    CorpGuid = yj.CorpGuid,
                                    tbCorpName = u.Name,
                                };
                    if (!string.IsNullOrEmpty(conditions))
                    {
                        ProjectRecord condition = JsonConvert.DeserializeObject<ProjectRecord>(conditions);
                        if (condition != null)
                        {
                            if (!string.IsNullOrEmpty(condition.ProjectName))
                            {
                                query = query.Where(q => q.ProjectName.Contains(condition.ProjectName));
                            }
                            if (condition.CorpGuid != null)
                            {
                                query = query.Where(q => q.CorpGuid == condition.CorpGuid);
                            }
                        }
                    }

                    count = query.ToList().Count();
                    totalZBMpney = query.ToList().Sum(a => a.ZbMoneyFloat);
                    if (pageSize == 0)//不分页
                    {
                        return query.ToList().OrderBy(p => p.ProjectID).ToList();
                    }
                    else
                    {
                        return query.ToList().OrderBy(p => p.ProjectID).Skip(pageCount * pageSize).Take(pageSize).ToList();
                    }
                case "JL":
                    if (areaCode == "02")
                    {
                        ////走青岛库
                    }
                    else
                    {
                        ////走省库
                    }
                    break;
                default:
                    break;
            }
            return null;
        }

        public override DTO.ProjectRecord GetProjectYJRecord(int projectID, string Code, string areaCode)
        {
            switch (Code)
            {
                case "DL":
                    var query = from yj in dbContext.dlyjRecord
                                join u in dbContext.T_Sys_Users
                                on yj.CorpGuid equals u.UserGuid
                                join a in dbContext.AreaSSQ
                                on yj.pAreaCode equals a.Code
                                into ayjs
                                from ayj in ayjs.DefaultIfEmpty()
                                where yj.ID == projectID
                                select new DTO.ProjectRecord
                                {
                                    ProjectID = yj.ID,
                                    dlyjGuid = yj.dlyjGuid,
                                    ProjectName = yj.Project,
                                    AreaCode = yj.pAreaCode,
                                    AreaName = ayj.Title,
                                    wtCorpName = yj.wtCorpName,
                                    NoticeDate = yj.NoticeDate,
                                    CheckCorp = yj.CheckCorp,
                                    ZbMoneyFloat = yj.ZbMoneyFloat,
                                    ContractDate = yj.ContractDate,
                                    NoticeCode = yj.NoticeCode,
                                    FcDate = yj.FcDate,
                                    KbDate = yj.KbDate,
                                    BidNum = yj.BidNum,
                                    isZBTZS = yj.isZBTZS,
                                    CorpGuid = yj.CorpGuid,
                                    tbCorpName = u.Name,
                                };
                    DTO.ProjectRecord record = query.FirstOrDefault();
                    IList<tb_dlyjRecordSub> sublist = dbContext.dlyjRecordSub.Where(s => s.dlyjGuid == record.dlyjGuid).ToList();
                    List<dlyjRecordSub> dlyjRecordSubList = new List<dlyjRecordSub>();
                    foreach (var item in sublist)
                    {
                        dlyjRecordSub dto = new dlyjRecordSub();
                        EntityHelper.ConvertEntity2OtherEntity(item, dto);
                        dlyjRecordSubList.Add(dto);
                    }
                    record.dlyjRecordSubList = JsonConvert.SerializeObject(dlyjRecordSubList);

                    IList<tb_dlyjRecordBid> bidlist = dbContext.dlyjRecordBid.Where(s => s.dlyjGuid == record.dlyjGuid).ToList();
                    List<dlyjRecordBid> dlyjRecordBidList = new List<dlyjRecordBid>();
                    foreach (var item in dlyjRecordBidList)
                    {
                        dlyjRecordBid dto = new dlyjRecordBid();
                        EntityHelper.ConvertEntity2OtherEntity(item, dto);
                        dlyjRecordBidList.Add(dto);
                    }
                    record.dlyjRecordBidList = JsonConvert.SerializeObject(dlyjRecordBidList);
                    return record;
                case "JL":
                    return null;
                default:
                    return null;
            }
        }

        #endregion
    }
}
